/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2012 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus.parser;

import static com.google.common.base.Preconditions.*;

/**
 * @author alb
 *
 * Adds tokens generated from a line of script embedded in a Platypus input file to the passed TokenList.
 */
public class ScriptSegmentTokenGen {

    private final String END_OF_SCRIPT = "[<<]";

    /**
     * The generated tokens will consist of either TokenType.SCRIPT (script contents) or END_OF_SCRIPT command.
     *
     * @param parsePoint where to start parsing
     * @param contentToParse the line of content to parse
     * @param tokens the TokenList to which the new tokens should be added
     * @param source the file # and line # of the current content
     * @param pState the parser state (in comment? in script? etc.)
     * @return the number of chars to move the parsePoint forward.
     */
    public int gen( int parsePoint, final String contentToParse,
                    final TokenList tokens, final Source source, ParserState pState )
    {
        checkArgument( parsePoint >= 0 && parsePoint < contentToParse.length() );
        checkNotNull( tokens );
        checkNotNull( contentToParse );
        checkNotNull( source );
        checkNotNull( pState );

        if( contentToParse.contains( END_OF_SCRIPT )) {  // script ends on this line
            int scriptEnding = contentToParse.indexOf( END_OF_SCRIPT );
            tokens.add( new Token( source, TokenType.SCRIPT, null,
                    contentToParse.substring( 0, scriptEnding ), null ));
            tokens.add( new Token( source, TokenType.COMMAND, END_OF_SCRIPT, END_OF_SCRIPT, null ));
            pState.inScript = false;
            return( parsePoint + scriptEnding + END_OF_SCRIPT.length() );
        }
        else { // did not encounter end of script, so rest of line is script.
            tokens.add( new Token( source, TokenType.SCRIPT, null, contentToParse, null ));
            return( Integer.MAX_VALUE );
        }
    }

}
